package com.tsmti.core.common.entity;

import com.tsmti.core.util.ObjectUtils;
import com.tsmti.core.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package：com.tsmti.core.common.entity
 * @Class：TreeNodeHelper
 * @Description： TODO
 * @Author：zcw
 * @Date：Created in 2018/4/4 17:15
 * @Company:
 * @Version：
 * @Modified By:
 */
public class TreeNodeHelper<ID extends Serializable> implements Serializable  {
    private static final long serialVersionUID = 2444638065060902858L;

    private List<BaseTreeNode<ID>> treeNodes;

    public static <T extends Serializable> TreeNodeHelper<T> create() {
        TreeNodeHelper<T> treeSortUtil = new TreeNodeHelper<T>();
        return treeSortUtil;
    }

    /**
     * 获得根节点
     *
     * @param
     */
    public List<TreeNode> getTopNodes() {
        List<TreeNode> list = new ArrayList<TreeNode>();
        for (BaseTreeNode<ID> treeNode : treeNodes) {
            if (treeNode.isRoot()) {
                list.add(new TreeNode(treeNode));
            }
        }
        return list;
    }

    /**
     * 解析根节点
     *
     * @param node
     */
    public void parseSubNode(TreeNode node) {
        List<TreeNode> newTreeNodes = new ArrayList<TreeNode>();
        for (BaseTreeNode<ID> treeNode : treeNodes) {
                  if (!ObjectUtils.isNullOrEmpty(treeNode.getParentId()) && node.getHref().equals(StringUtils.null2String(treeNode.getParentId()))) {
                TreeNode bootstrapTreeNode = new TreeNode(treeNode);
                newTreeNodes.add(bootstrapTreeNode);
                parseSubNode(bootstrapTreeNode);
                node.setNodes(newTreeNodes);
            }
        }
    }

    /**
     * 运行排序
     */
    @SuppressWarnings("unchecked")
    public List<TreeNode> sort(List<?> treeNodes) {
        this.treeNodes = (List<BaseTreeNode<ID>>) treeNodes;
        List<TreeNode> rootNodes = getTopNodes();
        for (TreeNode rootNode : rootNodes) {
            parseSubNode(rootNode);
        }
        this.treeNodes.clear();
        return rootNodes;
    }

}
